//
//  KeyboardView.m
//  NetPhone
//
//  Created by intel intel on 12-4-25.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "KeyboardView.h"
#import "GlobalVar.h"
#import "MsgPlaySound.h"
#define isRetina ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(640, 960), [[UIScreen mainScreen] currentMode].size) : NO)

@implementation KeyboardView
@synthesize delegate,bgPhonePadEdit;
@synthesize viewheight;

static KeyboardView *shareKeyboardViewInstance = nil;

+(KeyboardView *) sharedInstance{
    return shareKeyboardViewInstance;
}

-(UIImage *)getPressedKeyImage:(CGRect)rect sourceImage:(UIImage *)sourceImage
{
    if (isRetina || iPhone5) {
        rect = CGRectMake(rect.origin.x * 2, rect.origin.y * 2, rect.size.width*2, rect.size.height*2);
    }
	CGImageRef imageRef = sourceImage.CGImage;
    CGImageRef imageRefRect = CGImageCreateWithImageInRect(imageRef, rect);
    UIImage *imageRect = [[UIImage alloc] initWithCGImage: imageRefRect];
    return imageRect;
    
    
}



- (id)initWithFrame:(CGRect)frame
{
    self.blnShowKeyboard=YES;
    self = [super initWithFrame:frame];
    if (self) {
        
        shareKeyboardViewInstance=self;
        if ([[[UIDevice currentDevice]systemVersion]floatValue]>=7.0) {
            self.bounds=CGRectMake(0, 20, self.bounds.size.width, self.bounds.size.height);
        }
        UIView *topView = [[[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 52)]autorelease];
        topView.userInteractionEnabled=YES;
        [topView setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"bgPhonePadTop"]]];
        [self addSubview:topView];
        
        UIButton *btnPhoneNewAdd = [UIButton buttonWithType:UIButtonTypeCustom];
        [btnPhoneNewAdd setImage:[UIImage imageNamed:@"btnPhoneNewAdd"] forState:UIControlStateNormal];
        [btnPhoneNewAdd setImage:[UIImage imageNamed:@"btnPhoneNewAdd_Pressed"] forState:UIControlStateHighlighted];
        btnPhoneNewAdd.frame = CGRectMake(0, 0, 47, 52);
        [btnPhoneNewAdd addTarget:self action:@selector(phoneNewClicked:) forControlEvents:UIControlEventTouchUpInside];
        [topView addSubview:btnPhoneNewAdd];
        
        bgPhonePadEdit = [UIButton buttonWithType:UIButtonTypeCustom];
        [bgPhonePadEdit setBackgroundImage:[UIImage imageNamed:@"bgPhonePadEdit"] forState:UIControlStateNormal];
        [bgPhonePadEdit setBackgroundImage:[UIImage imageNamed:@"bgPhonePadEdit_Pressed"] forState:UIControlStateHighlighted];
        bgPhonePadEdit.frame = CGRectMake(47, 0, 226, 52);
        bgPhonePadEdit.titleLabel.font = [UIFont boldSystemFontOfSize:22];
        [bgPhonePadEdit setTitleEdgeInsets:UIEdgeInsetsMake(0, 2, 0, 50)];
       [topView addSubview:bgPhonePadEdit];
 
        UIButton *btnPhoneNewDelete = [UIButton buttonWithType:UIButtonTypeCustom];
        [btnPhoneNewDelete setImage:[UIImage imageNamed:@"btnPhoneNewDelete"] forState:UIControlStateNormal];
        [btnPhoneNewDelete setImage:[UIImage imageNamed:@"btnPhoneNewDelete_Pressed"] forState:UIControlStateHighlighted];
        btnPhoneNewDelete.frame = CGRectMake(270, 0, 50, 52);
        [btnPhoneNewDelete addTarget:self action:@selector(deletePhoneNumber:) forControlEvents:UIControlEventTouchDown];
        [btnPhoneNewDelete addTarget:self action:@selector(buttonTouchUpOutside:) forControlEvents:UIControlEventTouchUpOutside];
        [btnPhoneNewDelete addTarget:self action:@selector(buttonTouchUpOutside:) forControlEvents:UIControlEventTouchUpInside];
        [topView addSubview:btnPhoneNewDelete];
        UIView *keyView = [[[UIView alloc]initWithFrame:CGRectMake(0, 52, 320, 212)]autorelease];
        [self addSubview:keyView];
        
        
        UIImage *bgPhonePadNew = [UIImage imageNamed:@"bgPhonePadNew"];
        UIImage *bgPhonePadNew_Pressed = [UIImage imageNamed:@"bgPhonePadNew_Pressed"];
      
        UIImageView *keybord = [[[UIImageView alloc]initWithImage:bgPhonePadNew]autorelease];
        [keyView addSubview:keybord];
        
        
        for (int i=0;i<12; i++) {
            
            int dev = i/3;
            int mod = i%3;
            
            int width = 106;
            int left = 0 ;
            if (mod == 1) {
                left = 106;
                width = 108;
            }else if (mod == 2){
                left = 214;
            }
            
            UIButton *key = [UIButton buttonWithType:UIButtonTypeCustom];
            key.frame = CGRectMake(left, dev * 53, width, 53);
            key.tag = i;
            [key setImage:[self getPressedKeyImage:key.frame sourceImage:bgPhonePadNew_Pressed] forState:UIControlStateHighlighted];
            [key addTarget:self action:@selector(keyDown:) forControlEvents:UIControlEventTouchDown];
            [keyView addSubview:key];
            
            
        }
        
    }
    return self;
}

-(void)boda:(id)sender
{
    if (delegate) {
        [delegate callWithNumber:[bgPhonePadEdit titleForState:UIControlStateNormal]];
    }
}

-(void)phoneNewClicked:(UIButton *)button
{
    if (delegate) {
        [delegate addNewPerson:[bgPhonePadEdit titleForState:UIControlStateNormal]];
    }
}



-(void)setNewTitle:(NSString *)newTitle
{
    /*
    int infolenNum = newTitle.length;
    if (count<infolenNum)
    {
        NSMutableString *str = [NSMutableString stringWithFormat:@"%@",newTitle];
        if (infolenNum==4 || infolenNum==9)
        {
            if (![[str substringWithRange:NSMakeRange(3, 1)]isEqualToString:@"-"])
            {
                [str insertString:@"-" atIndex:3];
                newTitle = str;
            }else if(![[str substringWithRange:NSMakeRange(8, 1)]isEqualToString:@"-"])
            {
                [str insertString:@"-" atIndex:8];
                newTitle = str;
            }
            
        }
    }
    count = infolenNum;
     */
    [bgPhonePadEdit setTitle:newTitle forState:UIControlStateNormal];
    if (delegate)
    {
        //NSString *title =[newTitle stringByReplacingOccurrencesOfString:@"-" withString:@""];
        //NSLog(@"title===%@",title);
        [delegate keyboardValueChanged:newTitle];
    }
}


-(void)deletePhoneNumber:(UIButton *)keyButton
{
    NSString *title = [bgPhonePadEdit titleForState:UIControlStateNormal];
    if (!title) {
        title = @"";
    }
    if ([title length]>0) {
        NSString *newTitle = [title substringToIndex:[title length]-1];
        [self setNewTitle:newTitle];
        if ([newTitle length]==0) {
            [delegate showImage];
            [delegate showTabbarAndhideCallButton];
            
            
        }
    }
    [self performSelector:@selector(lazyButtontouchDown) withObject:nil afterDelay:1];
}

-(void)lazyButtontouchDown
{
    [self setNewTitle:@""];
    
    [delegate showImage];
    [delegate showTabbarAndhideCallButton];
    
}

- (void)buttonTouchUpInside:(UIButton *)keyButton
{
    [NSObject cancelPreviousPerformRequestsWithTarget:self
                                             selector:@selector(lazyButtontouchDown)
                                               object:nil];
}
- (void)buttonTouchUpOutside:(UIButton *)keyButton
{
    [NSObject cancelPreviousPerformRequestsWithTarget:self
                                             selector:@selector(lazyButtontouchDown)
                                               object:nil];
}

-(void)keyDown:(UIButton *)keyButton
{
    NSString *title = [bgPhonePadEdit titleForState:UIControlStateNormal];
    if (!title) {
        title = @"";
    }
    NSString *key;
    if (keyButton.tag < 9) {
        key = [NSString stringWithFormat:@"%d",keyButton.tag+1];
        preString=[NSString stringWithFormat:@"dtmf-%d",keyButton.tag+1];
    }else if (keyButton.tag == 9) {
        key = @"*";
        preString=@"dtmf-star";
    }else if (keyButton.tag == 10) {
        key = @"0";
        preString=@"dtmf-0";
    }else{
        key = @"#";
        preString=@"dtmf-pound";
    }
    NSString *newTitle = [NSString stringWithFormat:@"%@%@",title,key];
    if (newTitle.length>25)
    {
        return;
    }
    [self setNewTitle:newTitle];
    if (newTitle&&delegate) {
        [delegate hideImage];
        [delegate hideTabbarAndAddCallButton];
    }
    suString=@"caf";
    if ([[[NSUserDefaults standardUserDefaults]objectForKey:@"swithState"] isEqualToString:@"YES"])
    {
        [self playDialSound];
    }else
    {
        [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(playDialSound) object:nil];
    }
    
}

-(void)playDialSound
{
    MsgPlaySound* playSound=[[[MsgPlaySound alloc]initSystemSoundWithName:preString SoundType:suString]autorelease];
    [playSound play];
}
-(void)show
{
    self.blnShowKeyboard=YES;
	self.frame = CGRectMake(0, viewheight-264, 320, 264);
}

-(void)hide
{
    self.blnShowKeyboard=NO;
	self.frame = CGRectMake(0, viewheight-52, 320, 264);
	
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/

-(void)dealloc
{
    [super dealloc];
    shareKeyboardViewInstance = nil;
}

@end
